﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.IO;
using Yule8xCommon.Typelib;

namespace Yule8xCommon.Applib
{
    public class WechatUtil
    {
        /// <summary>
        /// 获取基础token
        /// </summary>
        /// <returns></returns>
        public static string GetToken()
        {
            HttpApplicationState application = System.Web.HttpContext.Current.Application;
            object token = application.Get("token");
            if (null != token)
            {
                WxTokenObject curtoken = token as WxTokenObject;
                if (null != curtoken && curtoken.expires_time >= DateTime.Now)
                {
                    return curtoken.access_token;
                }
            }
            string url = WechatUrls.GetBaseTokenUrl();
            string content = HttpUtil.HttpGet(url);
            WxTokenObject tokenobj = JSON.parse<WxTokenObject>(content);
            tokenobj.expires_time = DateTime.Now.AddSeconds(tokenobj.expires_in);
            application.Set("token", tokenobj);
            return tokenobj.access_token;
        }
    }
}